#==========相邻矩阵图============
#2023/08/18创建 Ivan Yan
#================================
 
library(RColorBrewer)
library(ggplot2)
library(reshape2)

library(readxl)
当前申请_专利权_人区域到受理局流向图 <- read_excel("当前申请（专利权）人区域到受理局流向图.xlsx", 
                                  +     col_types = c("text", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric", 
                                                      +         "numeric", "numeric", "numeric"))

df<-当前申请_专利权_人区域到受理局流向图
df<-df[1:10,1:11]
#df_sum<-apply(df[,2:ncol(df)],2,sum) #按列求和，用于后续排序
df_sum<-apply(df[,2:ncol(df)],1,sum)#按行求和，用于后续排序
order<-sort(df_sum,index.return=TRUE,decreasing =TRUE)#返回对象包含排序后的向量，以及排序的索引。
df_melt <- melt(df,id.vars = '当前申请(专利权)人区域')
colnames(df_melt)<-c("from","to","value")

#df_melt$to<-factor(df_melt$to,levels=df$'当前申请(专利权)人区域'[order$ix],order=TRUE)
df_melt$from<-factor(df_melt$from,levels=df$'当前申请(专利权)人区域'[order$ix],order=TRUE)


ggplot(df_melt, aes(x = from, y = to, fill = value,label=value)) +
  geom_tile(colour="black") +
  #geom_text(size=3,colour="white")+
  coord_equal()+
 scale_fill_gradientn(colors=brewer.pal(20,'YlGnBu'))+
  #scale_fill_gradientn(colors=brewer.pal(11,'BrBG'))+
  xlab('FROM')+
  ylab('TO')+
  #scale_fill_viridis(discrete=FALSE)+
  theme(
    axis.text.x = element_text(angle=90,hjust=1,colour='black'),
    axis.text.y = element_text(angle=0,hjust=1,colour='black')
  )

ggplot(df_melt, aes(x = from, y = to, fill = value,label=value)) +
  geom_tile(colour="black") +
  scale_fill_gradientn(colors=brewer.pal(9,'YlGnBu'))+
  xlab('FROM')+
  ylab('TO')+
  coord_equal()+
  theme(
    axis.text.x = element_text(angle=90,hjust=1,colour='black'),
    axis.text.y = element_text(angle=0,hjust=1,colour='black')
  )
